package com.jmb.apiplatform.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jmb.apiplatform.common.PageResult;
import com.jmb.apiplatform.mapper.UserLoginLogMapper;
import com.jmb.apiplatform.pojo.UserLogVO;
import com.jmb.apiplatform.pojo.UserLoginLogDao;
import com.jmb.apiplatform.service.UserLoginLogService;
import com.jmb.apiplatform.util.IPutil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserLoginLogServiceImpl implements UserLoginLogService {
    @Autowired
    private UserLoginLogMapper userLoginLogMapper;


    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址
     */
    @Override
    public String getUserIp(HttpServletRequest request) {
        IPutil iPutil = new IPutil();
        String[] headers = {"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "X-Real-IP"};
        for (String header : headers){
            String ip = iPutil.getHader(request, header);
            if (ip!=null && iPutil.isUnKnow(ip)){
                return iPutil.extractFirstIp(ip);
            }
        }
        return request.getRemoteAddr();

    }

    @Override
    public void insertUserLoginLog(UserLoginLogDao userLog) {
        userLoginLogMapper.insertUserLoginLog(userLog);
    }

    @Override
    public PageResult<UserLoginLogDao> list(UserLogVO userLogVO) {
        PageHelper.startPage(userLogVO.getPageNum(), userLogVO.getPageSize());
        List<UserLoginLogDao> userLogs = userLoginLogMapper.list(userLogVO);
        Page<UserLoginLogDao> p = (Page<UserLoginLogDao>)userLogs;
        return new PageResult(p.getTotal(),p.getResult());
    }

}




